package com.solocredit.finance.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.adapter.MullaRecyclerViewAdapter
import com.solocredit.finance.base.adapter.MullaViewHolderHelper
import com.solocredit.finance.base.utils.DensityUtils
import com.solocredit.finance.base.utils.dialog.BaseDialog
import com.solocredit.finance.base.utils.permission.OnPermissionCallback
import com.solocredit.finance.base.utils.permission.Permission
import com.solocredit.finance.base.utils.permission.XXPermissions
import com.solocredit.finance.databinding.DialogFleximolaPermListBinding
import com.solocredit.finance.databinding.ItemFleximolaPermListChildBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.utils.decoration.LinearSpacingItemDecoration
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaPermissionHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject


/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/25 13:41
 * @Annotation：权限列表
 */
class FlexiMolaPermListDialog: BaseDialog {
    lateinit var binding: DialogFleximolaPermListBinding
    private var mCallback: IDialogCallback? = null

    //权限描述列表
    private var permissionAdapter: PermissionItemAdapter? = null

    override fun initWindow() {
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
//        params?.height = MyApp.app.getPhoneHeight()
        window?.attributes = params
        window?.setWindowAnimations(R.style.picker_view_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    constructor(context: Context?) : super(context,R.style.LoadingDialog) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context,R.style.LoadingDialog) {
        mCallback = callback
    }

    override fun getRootView(): View {
        binding = DialogFleximolaPermListBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        initMullaRecyclerView()
    }

    override fun initListener() {
        setOnClickListener(binding.imgPerBack)
        setOnClickListener(binding.imgPerKefu)
        setOnClickListener(binding.btnDeny)
        setOnClickListener(binding.btnAgree)
//        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
//            when (isChecked) {
//                true -> {
//                    binding.btnAgree.isEnabled = true
//                }
//                false -> {
//                    binding.btnAgree.isEnabled = false
//                }
//            }
//        }
    }

    override fun initData() {
        val permissionList = arrayListOf<JSONObject>()
        permissionList.add(MullaPermissionHelper.takeMullaPerMSAGItem())
        permissionList.add(MullaPermissionHelper.takeMullaPerDeviceItem())
        permissionList.add(MullaPermissionHelper.takeMullaPerAplItem())
        permissionList.add(MullaPermissionHelper.takeMullaPerCameraItem())
        permissionList.add(MullaPermissionHelper.takeMullaPerFlashlightItem())
        permissionList.add(MullaPermissionHelper.takeMullaPerStorageItem())
        permissionList.add(MullaPermissionHelper.takeMullaPerPhoneBookItem())
        permissionList.add(MullaPermissionHelper.takeMullaPerAlbumItem())
        permissionAdapter?.let {
            it.data = permissionList
        }
    }

    override fun onViewClick(v: View?) {
        when(v?.id){
            R.id.imgPerBack -> {//返回
                dismiss()
            }
            R.id.imgPerKefu -> {
                mCallback?.onFlexiMolaKefuClick()
            }
            R.id.btnDeny -> {//拒绝
                SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LIST_STATUS,-1)
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_DENY,"Permission Page")
                dismiss()
                mCallback?.onFlexiMolaDenyClick()
            }
            R.id.btnAgree -> {//同意权限
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_AGREE,"Permission Page")
                if (!binding.checkBox.isChecked){
                    showMullaPermissionClickAgreedDialog()
                    return
                }
                SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LIST_STATUS,1)
                requestMullaFlowPermission()
            }
        }
    }

    /* 初始化列表 */
    @SuppressLint("ClickableViewAccessibility")
    private fun initMullaRecyclerView(){
//        binding.rvPermission.visibility = View.GONE
//        binding.rvPermission.setHasFixedSize(true)
//        binding.rvPermission.isNestedScrollingEnabled = false
//        binding.rvPermission.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        permissionAdapter = PermissionItemAdapter(binding.recyclerView)
        permissionAdapter?.setOnItemChildClickListener { _, _, position ->
            val item = permissionAdapter?.getItem(position)
        }
        binding.recyclerView.adapter = permissionAdapter
    }

    /**
     * 阅读与同意
     */
    private fun showMullaPermissionClickAgreedDialog(){
        val tipsDialog = TipsDialog(context,"Permission Page",object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnOk){
                    binding.checkBox.isChecked = true
                    binding.btnAgree.callOnClick()
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(false)
        tipsDialog.show()
        tipsDialog.setBtnText(MyApp.app.getString(R.string.btn_ok))
        tipsDialog.setTipsTitle(MyApp.app.getString(R.string.tips))
        tipsDialog.setTips(MyApp.app.getString(R.string.permission_agree_tips))
    }

    /**
     * 授权
     */
    private fun requestMullaFlowPermission(){
        XXPermissions.with(context)
            // 申请多个权限
            .permission(Permission.READ_SMS)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        mCallback?.onFlexiMolaAgreeClick()
                        dismiss()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(context,Permission.READ_SMS)
                    mCallback?.onFlexiMolaDenyClick()
                    dismiss()
                }
            })
    }

    class PermissionItemAdapter(recyclerView: RecyclerView?) : MullaRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.item_fleximola_perm_list) {

        override fun setItemChildListener(helper: MullaViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.itemLayout) //点击Item
        }

        override fun fillData(helper: MullaViewHolderHelper, position: Int, model: JSONObject) {
            val itemIcon = helper.getImageView(R.id.itemIcon)
            itemIcon.setImageResource(model.optInt("icon"))
            helper.setText(R.id.textTitle,model.optString("title"))

            val childItemLayout = helper.getView<LinearLayout>(R.id.childItemLayout)
            childItemLayout.removeAllViews()
            val itemList = model.optJSONArray("msgList")
            itemList?.let {
                for (i in 0..< itemList.length()){
                    val item = itemList.optJSONObject(i)
                    val itemView = ItemFleximolaPermListChildBinding.inflate(LayoutInflater.from(mContext))
                    val showTitle = item.optString("title")
                    if (showTitle.isNotEmpty()){
                        itemView.textTitle.text = showTitle
                        itemView.textTitle.visibility = View.VISIBLE
                    } else {
                        itemView.textTitle.visibility = View.GONE
                    }
                    itemView.textDes.text = item.optString("des")
                    childItemLayout.addView(itemView.root)
                }
            }
        }
    }

    interface IDialogCallback {
        //按钮点击
        fun onFlexiMolaKefuClick()
        fun onFlexiMolaDenyClick()
        fun onFlexiMolaAgreeClick()
    }


    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_PERMISSION_START,"")
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_PERMISSION_END,"")
    }
}